package com.heima.media.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    /**
     * 前置拦截（访问controller方法之前执行）
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //0. 判断请求路径
        String uri = request.getRequestURI();
        if (uri.contains("/login")){
            return true;
        }

        //1.从网关转发而来请求 从请求头中获取自媒体用户ID
        String userId = request.getHeader("userId");
        String userName = request.getHeader("userName");
        //2.判断用户id 封装对象 存入ThreadLocal方便后续web-service 取值
            //封装user对象
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            user.setUserName(userName);
            UserThreadLocalUtil.set(user);

        return true;

    }

    /**
     * 后置拦截（controller方法调用完后）
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       //将ThreadLocal中信息清除
        UserThreadLocalUtil.remove();
    }
    /**
     * 页面渲染完毕后拦截
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
